import Vue from 'vue'
import Vuex from 'vuex'
import permission from './modules/permission'
import {queryPermissionsByUser} from '@/api/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    get UserToken() {
      return localStorage.getItem('token')
    },
    set UserToken(value) {
        localStorage.setItem('token', value)
    },
    /* 导航菜单是否折叠 */
    isSidebarNavCollapse: false,
    /* 面包屑导航列表 */
    crumbList: [],
    namespaced: true,
    state: {
        permissionList: null /** 所有路由 */,
        sidebarMenu: [] /** 导航菜单 */,
        currentMenu: '' /** 当前active导航菜单 */,
        control_list: [] /** 完整的权限列表 */,
        avatar: ''/** 头像 */,
        account: ''/** 用户角色 */
    },
  },
  mutations: {
    LOGIN_IN(state, token) {
      state.UserToken = token
    },
    LOGIN_OUT(state) {
        state.UserToken = ''
    },
    toggleNavCollapse(state) {
        state.isSidebarNavCollapse = !state.isSidebarNavCollapse
    },
    setCrumbList(state, list) {
        state.crumbList = list
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
  },
  actions: {
     // 获取用户信息
     GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        let v_token = localStorage.getItem('token');
        let params = {token:v_token};
        queryPermissionsByUser(params).then(response => {
          const menuData = response.menu;
          // sessionStorage.setItem(USER_AUTH,JSON.stringify(authData));
          // sessionStorage.setItem(SYS_BUTTON_AUTH,JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
         console.log(error)
          reject(error)
        })
      })
    },
  },
  modules: {
    permission
  },
  getters:{
    addRouters:state => state.permission.addRouters
  }
})
